#!/usr/bin/env python

import logging
from google.appengine.api import urlfetch
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from xml.dom import minidom

class MainHandler(webapp.RequestHandler):
	
	def get(self):
		result = urlfetch.fetch(self.request.get('api_url'))
		self.response.headers['Content-Type'] = 'text/xml'
		
		if result.status_code == 200:
			logging.debug(result.content)
			xmldoc = minidom.parseString(result.content) 
			rsp_res = xmldoc.getElementsByTagName('rsp')[0].attributes['stat'].value 
			if rsp_res == 'ok':				
				circ = xmldoc.getElementsByTagName('entry')[0].attributes['circulation'].value 
				flare = "This feed has %s subscribers." % circ
				logging.debug("circ = %s" % circ)
			else:
				flare = xmldoc.getElementsByTagName('err')[0].attributes['msg'].value 
				logging.debug("err_msg = %s" % flare)
		else:
			flare = "An error has been encountered."
			
		logging.debug("flare = %s" % flare)
		self.response.out.write('<?xml version="1.0" ?><FeedFlare><Text>%s</Text></FeedFlare>' % flare)


application = webapp.WSGIApplication([('/', MainHandler)], debug=True)

def main():
	run_wsgi_app(application)


if __name__ == '__main__':
	main()